/**
 * 文档详情页面功能增强
 */

// 在文档加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    // 监听图片点击事件，实现图片预览放大功能
    initImagePreview();
    
    // 初始化元数据分组显示
    initMetadataSection();
    
    // 添加文档内容目录导航
    initContentNavigation();
});

/**
 * 图片预览功能
 */
function initImagePreview() {
    document.addEventListener('click', function(e) {
        // 检查点击的是否为文档内容中的图片
        if (e.target.tagName === 'IMG' && e.target.closest('.document-content, .image-preview')) {
            const img = e.target;
            
            // 创建模态预览容器
            const modal = document.createElement('div');
            modal.className = 'image-preview-modal';
            
            // 创建预览图片
            const previewImg = document.createElement('img');
            previewImg.src = img.src;
            previewImg.alt = img.alt;
            
            // 创建关闭按钮
            const closeBtn = document.createElement('button');
            closeBtn.className = 'close-preview-modal';
            closeBtn.innerHTML = '<i class="bi bi-x-lg"></i>';
            
            // 添加到页面
            modal.appendChild(previewImg);
            modal.appendChild(closeBtn);
            document.body.appendChild(modal);
            
            // 添加淡入效果
            setTimeout(() => modal.classList.add('show'), 10);
            
            // 点击模态窗口关闭
            modal.addEventListener('click', function(event) {
                if (event.target === modal || event.target === closeBtn || event.target.closest('.close-preview-modal')) {
                    modal.classList.remove('show');
                    setTimeout(() => {
                        document.body.removeChild(modal);
                    }, 300);
                }
            });
        }
    });
}

/**
 * 元数据分组功能
 */
function initMetadataSection() {
    const metadataElement = document.getElementById('document-metadata');
    if (!metadataElement) return;
    
    // 检查元数据区域是否已初始化
    if (metadataElement.querySelector('.metadata-section')) return;
    
    // 获取所有元数据项
    const metaItems = metadataElement.querySelectorAll('.doc-meta-item');
    if (metaItems.length === 0) return;
    
    // 清空当前内容
    const currentContent = metadataElement.innerHTML;
    metadataElement.innerHTML = '';
    
    // 创建基本信息部分
    const basicInfoSection = document.createElement('div');
    basicInfoSection.className = 'metadata-section';
    
    const basicInfoTitle = document.createElement('h3');
    basicInfoTitle.className = 'metadata-section-title';
    basicInfoTitle.textContent = '基本信息';
    
    basicInfoSection.appendChild(basicInfoTitle);
    
    // 添加原始元数据
    basicInfoSection.insertAdjacentHTML('beforeend', currentContent);
    
    // 添加到元数据容器
    metadataElement.appendChild(basicInfoSection);
    
    // 创建操作部分
    const actionsSection = document.createElement('div');
    actionsSection.className = 'metadata-section';
    
    const actionsTitle = document.createElement('h3');
    actionsTitle.className = 'metadata-section-title';
    actionsTitle.textContent = '文档操作';
    
    actionsSection.appendChild(actionsTitle);
    
    // 添加文档操作按钮
    actionsSection.innerHTML += `
        <div class="doc-meta-item action-item">
            <i class="bi bi-download"></i>
            <a href="#" onclick="downloadDocument(); return false;">下载文档</a>
        </div>
        <div class="doc-meta-item action-item">
            <i class="bi bi-printer"></i>
            <a href="#" onclick="printDocument(); return false;">打印文档</a>
        </div>
        <div class="doc-meta-item action-item">
            <i class="bi bi-share"></i>
            <a href="#" onclick="shareDocument(); return false;">分享文档</a>
        </div>
    `;
    
    // 添加到元数据容器
    metadataElement.appendChild(actionsSection);
}

/**
 * 初始化文档内容导航
 */
function initContentNavigation() {
    const contentElement = document.getElementById('document-content');
    const metadataElement = document.getElementById('document-metadata');
    
    if (!contentElement || !metadataElement) return;
    
    // 查找文档内容中的所有标题
    const headings = contentElement.querySelectorAll('h1, h2, h3, h4, h5, h6');
    
    if (headings.length <= 1) return; // 如果只有一个或没有标题，不创建目录
    
    // 创建目录部分
    const tocSection = document.createElement('div');
    tocSection.className = 'metadata-section';
    
    const tocTitle = document.createElement('h3');
    tocTitle.className = 'metadata-section-title';
    tocTitle.textContent = '目录导航';
    
    tocSection.appendChild(tocTitle);
    
    // 创建目录列表
    const tocList = document.createElement('div');
    tocList.className = 'toc-list';
    
    // 为每个标题创建导航项
    headings.forEach((heading, index) => {
        // 为标题添加ID，以便导航
        if (!heading.id) {
            heading.id = `heading-${index}`;
        }
        
        const level = parseInt(heading.tagName.substring(1));
        
        const tocItem = document.createElement('div');
        tocItem.className = `toc-item level-${level}`;
        tocItem.innerHTML = `
            <a href="#${heading.id}" class="toc-link">
                <i class="bi bi-dot"></i>
                <span>${heading.textContent}</span>
            </a>
        `;
        
        // 根据标题级别添加缩进样式
        tocItem.style.paddingLeft = `${(level - 1) * 12}px`;
        
        tocList.appendChild(tocItem);
    });
    
    tocSection.appendChild(tocList);
    
    // 将目录添加到元数据第一个位置
    metadataElement.insertBefore(tocSection, metadataElement.firstChild);
    
    // 点击导航项时滚动到相应位置
    document.querySelectorAll('.toc-link').forEach(link => {
        link.addEventListener('click', function(e) {
            e.preventDefault();
            
            const targetId = this.getAttribute('href').substring(1);
            const targetElement = document.getElementById(targetId);
            
            if (targetElement) {
                contentElement.scrollTo({
                    top: targetElement.offsetTop - 20,
                    behavior: 'smooth'
                });
            }
        });
    });
}

/**
 * 下载文档功能
 */
function downloadDocument() {
    // 获取当前文档信息
    const docTitle = document.getElementById('current-doc-title').textContent;
    const hasFileUrl = document.querySelector('.file-action-buttons a[download]');
    
    if (hasFileUrl) {
        // 如果页面上已有下载链接，触发点击
        hasFileUrl.click();
    } else {
        // 否则将当前文档内容保存为文本文件
        const content = document.getElementById('document-content').innerText;
        const blob = new Blob([content], { type: 'text/plain' });
        const url = URL.createObjectURL(blob);
        
        const a = document.createElement('a');
        a.href = url;
        a.download = `${docTitle}.txt`;
        a.style.display = 'none';
        
        document.body.appendChild(a);
        a.click();
        
        setTimeout(() => {
            document.body.removeChild(a);
            URL.revokeObjectURL(url);
        }, 100);
    }
    
    showActionNotification('文档已准备下载');
}

/**
 * 打印文档功能
 */
function printDocument() {
    const docContent = document.getElementById('document-content');
    const docTitle = document.getElementById('current-doc-title').textContent;
    
    // 创建打印友好的内容
    const printWin = window.open('', '_blank');
    printWin.document.write(`
        <html>
        <head>
            <title>${docTitle}</title>
            <style>
                body {
                    font-family: Arial, sans-serif;
                    line-height: 1.6;
                    color: #333;
                    padding: 20px;
                    max-width: 800px;
                    margin: 0 auto;
                }
                h1, h2, h3, h4, h5, h6 {
                    margin-top: 20px;
                    margin-bottom: 10px;
                }
                img {
                    max-width: 100%;
                }
                pre {
                    background-color: #f5f5f5;
                    padding: 15px;
                    border-radius: 5px;
                    overflow-x: auto;
                }
                code {
                    font-family: Consolas, monospace;
                }
                @media print {
                    body {
                        padding: 0;
                    }
                }
            </style>
        </head>
        <body>
            <h1>${docTitle}</h1>
            ${docContent.innerHTML}
        </body>
        </html>
    `);
    
    printWin.document.close();
    
    // 延迟一下，等待资源加载
    setTimeout(() => {
        printWin.print();
        printWin.close();
    }, 500);
    
    showActionNotification('文档已发送到打印队列');
}

/**
 * 分享文档功能
 */
function shareDocument() {
    // 获取当前文档ID和标题
    const docId = window.location.pathname.split('/').pop();
    const docTitle = document.getElementById('current-doc-title').textContent;
    
    // 创建分享链接
    const shareUrl = `${window.location.origin}/document/${docId}`;
    
    // 创建模态分享窗口
    const shareModal = document.createElement('div');
    shareModal.className = 'share-modal';
    
    shareModal.innerHTML = `
        <div class="share-modal-content">
            <div class="share-modal-header">
                <h3>分享文档: ${docTitle}</h3>
                <button class="close-share-modal"><i class="bi bi-x"></i></button>
            </div>
            <div class="share-modal-body">
                <div class="share-url-container">
                    <input type="text" class="share-url-input" value="${shareUrl}" readonly />
                    <button class="copy-share-url"><i class="bi bi-clipboard"></i> 复制</button>
                </div>
                <div class="share-options">
                    <button class="share-option" data-type="email">
                        <i class="bi bi-envelope"></i> 通过邮件分享
                    </button>
                    <button class="share-option" data-type="wechat">
                        <i class="bi bi-wechat"></i> 微信分享
                    </button>
                    <button class="share-option" data-type="clipboard">
                        <i class="bi bi-clipboard"></i> 复制链接
                    </button>
                </div>
            </div>
        </div>
    `;
    
    document.body.appendChild(shareModal);
    
    // 添加淡入效果
    setTimeout(() => shareModal.classList.add('show'), 10);
    
    // 关闭分享窗口
    shareModal.querySelector('.close-share-modal').addEventListener('click', () => {
        shareModal.classList.remove('show');
        setTimeout(() => {
            document.body.removeChild(shareModal);
        }, 300);
    });
    
    // 点击模态窗口背景关闭
    shareModal.addEventListener('click', function(e) {
        if (e.target === shareModal) {
            shareModal.classList.remove('show');
            setTimeout(() => {
                document.body.removeChild(shareModal);
            }, 300);
        }
    });
    
    // 复制分享链接
    shareModal.querySelector('.copy-share-url').addEventListener('click', function() {
        const urlInput = shareModal.querySelector('.share-url-input');
        urlInput.select();
        document.execCommand('copy');
        
        // 显示复制成功提示
        this.innerHTML = '<i class="bi bi-check"></i> 已复制';
        this.classList.add('copied');
        
        setTimeout(() => {
            this.innerHTML = '<i class="bi bi-clipboard"></i> 复制';
            this.classList.remove('copied');
        }, 2000);
    });
    
    // 监听分享选项点击
    shareModal.querySelectorAll('.share-option').forEach(option => {
        option.addEventListener('click', function() {
            const shareType = this.getAttribute('data-type');
            
            switch(shareType) {
                case 'email':
                    window.open(`mailto:?subject=${encodeURIComponent(`分享文档: ${docTitle}`)}&body=${encodeURIComponent(`查看文档: ${shareUrl}`)}`);
                    break;
                case 'wechat':
                    alert('微信分享功能正在开发中');
                    break;
                case 'clipboard':
                    navigator.clipboard.writeText(shareUrl).then(() => {
                        showActionNotification('链接已复制到剪贴板');
                    });
                    break;
            }
        });
    });
    
    showActionNotification('分享面板已打开');
}

/**
 * 显示操作通知
 */
function showActionNotification(message) {
    // 检查是否已有通知
    let notification = document.querySelector('.action-notification');
    
    if (!notification) {
        // 创建通知元素
        notification = document.createElement('div');
        notification.className = 'action-notification';
        document.body.appendChild(notification);
    }
    
    // 设置通知内容
    notification.textContent = message;
    notification.classList.add('show');
    
    // 自动隐藏
    setTimeout(() => {
        notification.classList.remove('show');
    }, 3000);
} 